//
//  BCacheMapTool.m
//  Bullet
//
//  Created by  on 2019/9/19.
//  Copyright © 2019 . All rights reserved.
//

#import "BCacheMapTool.h"
#import "BFileManagerTool.h"
#import "VideoCacheHelper.h"
#import "BConst.h"
#import "BM3U8LocalFileParser.h"

@implementation BCacheMapTool


- (void)deleteCacheVideoPath:(NSString *)cachePath{
    [[BFileManagerTool tool] deleteCacheFolder:[[[BFileManagerTool tool] fileSaveCachePath] stringByAppendingPathComponent:cachePath]];
}

#pragma mark - 缓存记录

- (void)addCacheVideoPath:(NSString *)cachePath{
    
    id mapData = [[NSUserDefaults standardUserDefaults] objectForKey:VIDEO_LOCAL_CACHE_MAP_KEY];
    
    NSDictionary *dic = [NSDictionary dictionary];
    if(mapData && [mapData isKindOfClass:[NSDictionary class]]){
        dic = (NSDictionary *)mapData;
    }
    NSMutableDictionary *mutiDic = [NSMutableDictionary dictionaryWithDictionary:dic];
    
    BOOL containerThisPath = NO;
    NSString *containerKey = @"";
    for (NSString *key in mutiDic.allKeys) {
        NSString *valueStr = [mutiDic objectForKey:key];
        if([cachePath isEqualToString:valueStr]){
            containerThisPath = YES;
            containerKey = key;
            break;
        }
    }
    
    if(containerThisPath && [mutiDic.allKeys containsObject:containerKey]){
        [mutiDic removeObjectForKey:containerKey];
    }
//    BLog(@"video pre cache map is %@",mutiDic);
    if(mutiDic.allKeys.count >= self.maxMapLength){
        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES];
        NSArray *sortKeys = [mutiDic.allKeys sortedArrayUsingDescriptors:@[sort]];
        NSInteger deleteNum = sortKeys.count - self.maxMapLength + 1;
        for (int i = 0; i < deleteNum; i++) {
            NSString *url = [mutiDic objectForKey:sortKeys[i]];
            [self deleteCacheVideoPath:url];
            [mutiDic removeObjectForKey:sortKeys[i]];
        }
    }
    [mutiDic setValue:cachePath forKey:[[NSDate date] dateToString:VIDEO_CACHE_TIME_FORMATE_KEY]];
    
//    BLog(@"video current cache map is %@",mutiDic);
    [[NSUserDefaults standardUserDefaults] setObject:mutiDic forKey:VIDEO_LOCAL_CACHE_MAP_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}


#pragma mark - file exist

- (BOOL)localFileIsExist:(NSString *)urlStr preload:(BOOL)preload{
    NSString *cachePath = [[BFileManagerTool tool] videoCachePathForUrl:urlStr preload:preload];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if([fileManager fileExistsAtPath:cachePath]){
        if(![cachePath containsString:@".m3u8"]){
            return YES;
        }
        BOOL needParse = YES;
        BOOL hasExist = YES;
        NSMutableArray *parserPathA = [NSMutableArray array];
        [parserPathA addObject:cachePath];
        do {
            
            NSArray *m3u8Parsers = [parserPathA mutableCopy];
            [parserPathA removeAllObjects];
            
            if(m3u8Parsers.count > 0){
                for (NSString *path in m3u8Parsers) {
                    BM3U8LocalFileParser *localParser = [BM3U8LocalFileParser parserWithPath:path];
                    
                    if(![localParser allFileIsExist].isAllExist){
                        needParse = NO;
                        hasExist = NO;
                        break;
                    }
                    else if(localParser.m3u8urlA.count > 0){
                        [parserPathA addObjectsFromArray:localParser.m3u8DirectPA];
                    }
                    else
                    {
                        needParse = NO;
                    }
                        
                }
            }
        } while (needParse);
        return hasExist;
    }
    return NO;
}

#pragma mark - clear

- (void)clearAllLoadingCacheAndFolder{
    id loadingPathData = [[NSUserDefaults standardUserDefaults] objectForKey:VIDEO_LOADING_CACHE_MAP_KEY];
    
    NSMutableDictionary *mutDic = [NSMutableDictionary dictionary];
    if(loadingPathData && [loadingPathData isKindOfClass:[NSDictionary class]]){
        mutDic = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary *)loadingPathData];
    }
    for (NSString *key in mutDic.allKeys) {
        id cacheP = [mutDic objectForKey:key];
        if(!IS_NULL_STR(cacheP)){
            [self deleteCacheVideoPath:cacheP];
        }
    }
    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:VIDEO_LOADING_CACHE_MAP_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)clearMap{
    [[NSUserDefaults standardUserDefaults] setObject:@{} forKey:VIDEO_LOCAL_CACHE_MAP_KEY];
    [[NSUserDefaults standardUserDefaults] setObject:@{} forKey:VIDEO_FINISHED_CACHE_MAP_KEY];
    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:VIDEO_LOADING_CACHE_MAP_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (instancetype)tool{
    static BCacheMapTool *tool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [[BCacheMapTool alloc] init];
        tool.maxMapLength = 10;
    });
    return tool;
}

@end
